/*
 * @Author: ZAL 2177624751@qq.com
 * @Date: 2025-02-05 15:07:42
 * @LastEditors: ZAL 2177624751@qq.com
 * @LastEditTime: 2025-02-05 15:07:51
 * @FilePath: \asset-management-webc:\Users\21776\Desktop\毕设\shop_app_vue3\store\productStore.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
//商品数据缓存

import { defineStore } from 'pinia';
import {
  getCategories,
  searchProducts,
  getProductDetail,
  getRecommendProducts
} from '../api/product.js';

export const useProductStore = defineStore('product', {
  state: () => ({
    // 商品分类列表
    categories: [],
    // 商品列表
    productList: [],
    // 当前商品详情
    currentProduct: {
      productId: null,
      productName: '',
      price: 0,
      discountPrice: 0,
      sales: 0,
      unit: '件',
      packaging: '盒',
      description: '',
      mainImage: '',
      detailImages: [],
      isHot: false,
      isRecommend: false,
      categoryName: '',
      origin: '未知',
      shelfLife: '请查看包装',
      storage: '常温保存',
      stock: 0,
      specifications: '{}',
      nutrition: '{}',
      shippingFee: 0,
      storageMethod: '常温保存',
      isFavorite:0,
    },
    // 推荐商品列表
    recommendProducts: [],
    // 搜索历史
    searchHistory: [],
    // 当前分类ID
    currentCategoryId: null,
    // 当前搜索关键词
    currentKeyword: '',
    // 加载状态
    loading: {
      categories: false,
      products: false,
      detail: false,
      recommend: false,
      search: false
    },
    // 缓存时间（用于控制数据刷新）
    cacheTime: {
      categories: 0,
      products: 0,
      recommend: 0
    }
  }),

  getters: {
    // 获取分类列表
    getCategoryList: (state) => state.categories,
    // 获取商品列表
    getProductList: (state) => state.productList,
    // 获取当前商品
    getCurrentProduct: (state) => state.currentProduct,
    // 获取推荐商品
    getRecommendProducts: (state) => state.recommendProducts,
    // 获取搜索历史
    getSearchHistory: (state) => state.searchHistory,
    // 获取加载状态
    isLoading: (state) => (type) => state.loading[type],
    // 获取商品详情图片列表
    getDetailImages: (state) => {
      const mainImage = state.currentProduct.mainImage;
      const detailImages = state.currentProduct.detailImages || [];
      const images = Array.isArray(detailImages) ? detailImages : [];
      return mainImage ? [mainImage, ...images] : images;
    }
  },

  actions: {
    // 加载商品分类
    async loadCategories() {
      if (this.loading.categories) return;
      
      try {
        this.loading.categories = true;
        const res = await getCategories();
        if (res.code === 200) {
          this.categories = res.data;
          this.cacheTime.categories = Date.now();
        }
        return res;
      } catch (error) {
        console.error('加载商品分类失败:', error);
        throw error;
      } finally {
        this.loading.categories = false;
      }
    },

    // 搜索商品
    async searchProducts(keyword) {
      if (this.loading.search) return;
      
      try {
        this.loading.search = true;
        this.currentKeyword = keyword;
        
        if (keyword && !this.searchHistory.includes(keyword)) {
          this.searchHistory.unshift(keyword);
          if (this.searchHistory.length > 10) {
            this.searchHistory.pop();
          }
          uni.setStorageSync('searchHistory', this.searchHistory);
        }

        const res = await searchProducts(keyword);
        if (res.code === 200) {
          this.productList = res.data;
        }
        return res;
      } catch (error) {
        console.error('搜索商品失败:', error);
        throw error;
      } finally {
        this.loading.search = false;
      }
    },

    async loadProductDetail(id) {
      if (this.loading.detail) return;
      
      try {
        this.loading.detail = true;
        const res = await getProductDetail(id);
        if (res.code === 200 && res.data) {
          this.currentProduct = {
            productId: res.data.id,
            productName: res.data.title,
            price: res.data.price,
            sales: res.data.sales || 0,
            unit: res.data.unit || '件',
            packaging: res.data.packaging || '盒',
            description: res.data.description,
            mainImage: res.data.img_url || res.data.mainImage,
            detailImages: res.data.detailImages || [],
            isHot: res.data.isHot || false,
            isRecommend: res.data.isRecommend || false,
            categoryName: res.data.categoryName || '',
            origin: res.data.origin || '未知',
            shelfLife: res.data.shelfLife || '请查看包装',
            storage: res.data.storage || '常温保存',
            stock: res.data.stock ,
            specifications: res.data.specifications,
            nutrition: res.data.nutrition ,
            discountPrice: res.data.discountPrice ,
            shippingFee: res.data.shippingFee ,
            storageMethod: res.data.storageMethod ,
            isFavorite:res.data.isFavorite,
          };
        }
        return res;
      } catch (error) {
        console.error('加载商品详情失败:', error);
        throw error;
      } finally {
        this.loading.detail = false;
      }
    },

    // 加载推荐商品
    async loadRecommendProducts(limit = 6) {
      if (this.loading.recommend) return;
      
      try {
        this.loading.recommend = true;
        const res = await getRecommendProducts(limit);
        if (res.code === 200) {
          this.recommendProducts = res.data;
          this.cacheTime.recommend = Date.now();
        }
        return res;
      } catch (error) {
        console.error('加载推荐商品失败:', error);
        throw error;
      } finally {
        this.loading.recommend = false;
      }
    },

    clearSearchHistory() {
      this.searchHistory = [];
      uni.removeStorageSync('searchHistory');
    },

    initStore() {
      const history = uni.getStorageSync('searchHistory');
      if (history) {
        this.searchHistory = history;
      }
    },
    resetProductList() {
      this.productList = [];
      this.currentCategoryId = null;
      this.currentKeyword = '';
    },

    // 清除商品详情
    clearCurrentProduct() {
      this.currentProduct = {
        productId: null,
        productName: '',
        price: 0,
        discountPrice: 0,
        sales: 0,
        unit: '件',
        packaging: '盒',
        description: '',
        mainImage: '',
        detailImages: [],
        isHot: false,
        isRecommend: false,
        categoryName: '',
        origin: '未知',
        shelfLife: '请查看包装',
        storage: '常温保存',
        stock: 0,
        specifications: '{}',
        nutrition: '{}',
        shippingFee: 0,
        storageMethod: '常温保存'
      };
    }
  }
});